package org.jeecg.modules.company.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.company.dto.ComAdminUserDto;
import org.jeecg.modules.company.entity.ComUser;
import org.jeecg.modules.company.service.IComAdminUserService;
import org.jeecg.modules.company.service.IComInfoService;
import org.jeecg.modules.company.service.IComUserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 企业人员
 * @Author: jeecg-boot
 * @Date:   2020-03-15
 * @Version: V1.0
 */
@Api(tags="企业人员")
@RestController
@RequestMapping("/company/comUser")
@Slf4j
public class ComUserController extends JeecgController<ComUser, IComUserService> {
	@Autowired
	private IComUserService comUserService;
	@Autowired
	private IComAdminUserService comAdminUserService;
	 @Autowired
	 private IComInfoService comInfoService;

	/**
	 * 分页列表查询
	 *
	 * @param comUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "企业人员-分页列表查询")
	@ApiOperation(value="企业人员-分页列表查询", notes="企业人员-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ComUser comUser,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String token = req.getHeader("X-Access-Token");
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("查看失败，用户不存在！");
		}
		String username = JwtUtil.getUsername(token);
		String id=comInfoService.getByUserName(username);
		comUser.setCompanyId(id);
		QueryWrapper<ComUser> queryWrapper = QueryGenerator.initQueryWrapper(comUser, req.getParameterMap());
		Page<ComUser> page = new Page<ComUser>(pageNo, pageSize);
		IPage<ComUser> pageList = comUserService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 /**
	  * 企业员工检索
	  *
	  * @param comUser
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "企业人员-分页列表查询")
	 @ApiOperation(value="企业人员-分页列表查询", notes="企业人员-分页列表查询")
	 @GetMapping(value = "/listByKey")
	 public Result<?> listByKey(ComUser comUser,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 String token = req.getHeader("X-Access-Token");
		 if(oConvertUtils.isEmpty(token)) {
			 return Result.error("查看失败，用户不存在！");
		 }
		 String username = JwtUtil.getUsername(token);
		 String id=comInfoService.getByUserName(username);
		 comUser.setCompanyId(id);
		 IPage<ComUser> pageList = comUserService.listByKey(pageNo,pageSize,comUser);
		 return Result.ok(pageList);
	 }
	/**
	 *   添加
	 *
	 * @param comUser
	 * @return
	 */
	@AutoLog(value = "企业人员-添加")
	@ApiOperation(value="企业人员-添加", notes="企业人员-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ComUser comUser,HttpServletRequest req) {
		String token = req.getHeader("X-Access-Token");
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("查看失败，用户不存在！");
		}
		String username = JwtUtil.getUsername(token);
		String id=comInfoService.getByUserName(username);
		//重复性校验
		if(comUser.getUtype()==null){
			return Result.error("请选择人员类别！");
		}else{
			if(comUser.getUtype()==1){
				Map paramMap=new HashMap();
				paramMap.put("utype",comUser.getUtype());
				paramMap.put("company_id",id);
				if(comUserService.checkUnique(paramMap)){
					return Result.error("已录入企业法人");
				}
			}
		}

		comUser.setCompanyId(id);
		comUserService.save(comUser);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param comUser
	 * @return
	 */
	@AutoLog(value = "企业人员-编辑")
	@ApiOperation(value="企业人员-编辑", notes="企业人员-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ComUser comUser) {
		comUserService.updateById(comUser);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业人员-通过id删除")
	@ApiOperation(value="企业人员-通过id删除", notes="企业人员-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		comUserService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业人员-批量删除")
	@ApiOperation(value="企业人员-批量删除", notes="企业人员-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.comUserService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业人员-通过id查询")
	@ApiOperation(value="企业人员-通过id查询", notes="企业人员-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ComUser comUser = comUserService.getById(id);
		if(comUser==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(comUser);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param comUser
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ComUser comUser) {
         ComAdminUserDto  dto = comAdminUserService.getUserCompanyByUserId();
         if(dto!=null) {
        	 comUser.setCompanyId(dto.getCompanyId());
         }
         return super.exportXls(request, comUser, ComUser.class, "企业人员");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            //params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ComUser> comUsers = ExcelImportUtil.importExcel(file.getInputStream(), ComUser.class, params);
                //comInfoService.saveBatch(comInfos);
              //根据当前登录用户名获取所属企业。
                String companyId ="";
                ComAdminUserDto  dto = comAdminUserService.getUserCompanyByUserId();
                if(dto!=null) {
                	  companyId = dto.getCompanyId();
                }else {
                	return Result.error("您未归属于任何企业，导入失败.");
                }
                for (ComUser comuser : comUsers) {
                	if(null != dto) {
						comuser.setCompanyId(companyId);
                	}
                	comUserService.save(comuser);
                }
                return Result.ok("员工数据导入成功！数据行数：" + comUsers.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("员工数据导入失败.");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                	log.error(e.getMessage(), e);
                }
            }
        }
        return Result.error("员工数据导入失败！");
    }

	 /**
	  * 查询省
	  * @return
	  */
	 @AutoLog(value = "查询省")
	 @ApiOperation(value="查询省", notes="查询省")
	 @GetMapping(value = "/getProvince")
    public Result<?> getProvince(){
		List resultList=comUserService.getProvince();
		return Result.ok(resultList);
	}

	 /**
	  * 查询城市
	  * @return
	  */
	 @AutoLog(value = "查询城市")
	 @ApiOperation(value="查询城市", notes="查询城市")
	 @GetMapping(value = "/getCityByPid")
	public Result getCityByPid(@RequestParam(name="fatherid",required=true) String fatherid){
	 	Map paramMap=new HashMap();
	 	paramMap.put("fatherid",fatherid);
		List resultList=comUserService.getCityByPid(paramMap);
		return Result.ok(resultList);
	}
}
